<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发送AJAX请求</title>
</head>

<body>

    <script>
        //发送AJAX请求，返回的结果是Promise对象
        function sendAJAX(url) {
            return new Promise((resolve, reject) => {
                //1.创建对象
                const x = new XMLHttpRequest();
                //2.初始化
                x.open('GET', url);
                //3.发送
                x.send();
                //4.事件绑定 
                x.onreadyStatechange = function () {
                    if (x.readyState === 4) {
                        if (x.status >= 200 && x.status < 300) {
                            //成功
                            resolve(x.response);
                        } else {
                            reject(x.status);
                        }
                    }
                }
            });
        }
        //promise then 方法测试
        // sendAJAX("https://api.apiopen.top/getJoke").then(value => {
        //     console.log(value);
        // }, reason => { });


        //async与await测试
        async function main() {
            //发送Ajax请求
            let result = await sendAJAX("https://api.apiopen.top/getJoke");
            console.log(result);
            //再次测试
            let tianqi = await sendAJAX("http://api.k780.com/?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json");
            console.log(tianqi);
        }





        // const res = sendAJAX("https://api.apiopen.top/getJoke");
        // console.log(111);
        // console.log(res);
        // console.log(111);


    </script>

</body>

</html>'